/**
 * 
 */
package org.pump.client.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.pump.client.main.MysqlDecoder;
import org.pump.client.type.LengthCodedBinary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 * 
 */
public class ResultPack extends PacketBody {
	private static final Logger mylog = LoggerFactory
			.getLogger(ResultPack.class);
	short resulttype;

	public static ResultPack readBuffer(IoBuffer in, int len,
			IoSession mysession, Packet prevpack, int curnum) {
		short restype = in.getUnsigned();

		ResultPack respack = null;

		if (restype == 0) {
			if (MysqlDecoder.CLIENT_AUTH_STAGE == curnum) {
				OkPack mypack = OkPack.readBuffer(in, len - 1);
				if (mypack == null) {
					mylog.error("read ok packet fail");
					return null;
				}
				Integer cmdstage = new Integer(
						MysqlDecoder.CLIENT_COMMAND_STAGE);
				mysession
						.setAttribute(MysqlDecoder.DECODER_STAGE_KEY, cmdstage);
				mylog.debug("auth ok,the client status is command_waitting");
				respack = mypack;
			} else if (MysqlDecoder.CLIENT_COMMAND_STAGE == curnum) {
				BinlogEvent myevent = BinlogEvent.readBuffer(in, len - 1,
						prevpack);
				if (myevent == null) {
					mylog.error("read binglog event fail");
					return null;
				}
				respack = myevent;
			}
		} else if (restype == 255) {
			ErrorPack mypack = ErrorPack.readBuffer(in, len - 1);
			if (mypack == null) {
				mylog.error("read error packet fail");
				return null;
			}
			respack = mypack;
			Integer errorstage = new Integer(MysqlDecoder.SERVER_AUTH_ERROR);
			mysession.setAttribute(MysqlDecoder.DECODER_STAGE_KEY, errorstage);

			if (MysqlDecoder.CLIENT_AUTH_STAGE == curnum) {
				mylog.info("auth fail,mypump will close the session");

			} else if (MysqlDecoder.CLIENT_COMMAND_STAGE == curnum) {
				mylog.info("command fail,mypump will close the session");
			}
		} else if (restype == 254) {
			EofPacket mypack = EofPacket.readBuffer(in, len - 1);
			if (mypack == null) {
				mylog.error("read error packet fail");
				return null;
			}
			mylog.info("receive eof packet,master stop communication,please check master["
					+ mypack + "]");
			Integer errorstage = new Integer(MysqlDecoder.SERVER_DATA_EOF);
			mysession.setAttribute(MysqlDecoder.DECODER_STAGE_KEY, errorstage);
			respack = mypack;
		} else {
			mylog.error("unsupported result packet type");
			return null;
		}
		respack.resulttype = restype;
		return respack;
	}
}
